<?php

	namespace Admin\Controller;
	use Think\Controller;

	
	class GoodsController extends Controller{


		public function index(){
			$cid = $_GET['cid'];  //分类Id号
			$listRows = 5;
			$goodModel = D('Goods');
			$brandArr = $this ->getBrandArr();

			//总记录数
			$counts = $goodModel -> getAllspuByCid($cid,'',true);
			$page = new \Think\Page($counts,$listRows);
			$firstRow = (($_GET['p'] > ceil($counts/$listRows) ? ceil($counts/$listRows):$_GET['p'])-1)*$listRows<0?0:(($_GET['p'] > ceil($counts/$listRows) ? ceil($counts/$listRows):$_GET['p'])-1)*$listRows;
			$pagelist = $page -> show();

			//分类树输出
			$catModel = D('Category');
			$list = $catModel ->field(true)->select();

			$catArr  = $catModel->getSubTree($list,0);
			// echo '<pre>';
			// print_r($catArr);
			// echo '</pre>';
			// exit;

			// //分页输出记录
			$spuArr = $goodModel -> getAllspuByCid($cid,$firstRow.','.$listRows,false);

			//判断是不是ajax请求
			if(IS_AJAX){

				$this -> ajaxReturn(['page'=>$pagelist,'html'=>$this -> html($spuArr)]);
			}else{

				$this -> assign('brandArr',$brandArr);
				$this -> assign('arr',$catArr);
				$this -> assign('page',$pagelist); //分页样式输出
				$this -> assign('spuArr',$spuArr);//spuArr输出
				$this -> display('Goods/index');
			}
		}

		/**
		 * [addIndex 添加spu的输出页面函数]
		 */
		public function addIndex(){
			$catModel = D('Category');
			$list = $catModel ->field(true)->select();
			$arr  = $catModel->getSubTree($list,0);

			//获取品牌数组
			$brandArr = $this -> getBrandArr();

			$this -> assign('arr',$arr); //分配分类数组变量
			$this -> assign('brandArr',$brandArr);
			$this -> display();
			
		}

		/**
		 * [html 输出spu信息的表格函数]
		 * @param  [type] $spuArr [description]
		 * @return [type]         [description]
		 */
		public function html($spuArr){
			$html = '';
			if(empty($spuArr)){
				$html = '暂时没有数据!';
			}else{
				foreach($spuArr as $key => $spu){
				$html .= '<tr>
							<td>'.$spu['spuid'].'</td>
							<td><img src="'.GOODSIMGPATH.$spu['imgurl'].'" width="50px" height="50px" alt="">'.$spu['name'].'</td>
							<td>'.$spu['price'].'</td>
							<td>'.$spu['totalstore'].'</td>
							<td>'.($spu['status']==1?'已上架':'已下架').'</td>
							<td>'.date('Y-m-d',$spu['addtime']).'</td>
							<td>
								<button type="button" data-spuid="'.$spu['spuid'].'" class="btn btn-danger btn-xs delBtn">删除</button>
								<button type="button" class="btn btn-info btn-xs btn-look" data-spuid="'.$spu['spuid'].'">查看sku</button>
								<a href="'.U('Goods/addsku',['spuid'=>$spu['spuid']]).'"><button type="button" class="btn btn-info btn-xs btn-addsku" data-spuid="'.$spu['spuid'].'">添加sku</button></a>
								<a href="javascript:void(0)"><button type="button" class="btn btn-success btn-xs spueditBtn" data-spuid="'.$spu['spuid'].'" data-spuname="'.$spu['name'].'">编辑</button></a>
							</td>
						</tr>';
				}
			}
			

			return $html;
		}



		public function getBrandArr(){
			$brand = M('brand');
			$brandArr = M('brand') -> select();
			return $brandArr;
		}

		/**
		 * [getidProperty 根据分类来获得此分类下所有属性的数组]
		 * @return [type] [description]
		 */
		public function getidProperty(){
			if(empty(I('post.cid'))){
				echo 1;
			}else{

				//查询该分类下的所有属性和值
				$arr = [];
				$cat_proModel = M('cat_pro');
				$proModel = M('Property');

					//遍历分类属性表		
					if($data = $cat_proModel -> where(['catId'=>I('post.cid')]) -> select()){
					
						foreach($data as $key => $val){ 
							$proArr= $proModel ->field('pro.name proname,proval.name value,pro.id proid,proval.id valid')->alias('pro') -> join('__PROVAL__ proval on proval.proid = pro.id') -> where('pro.id='.$val['proid'])->select();
							foreach($proArr as $k => $value){
								$arr[$value['proname']][]=$value;
							}
						}

						$this -> assign('arr',$arr);
						$this -> display('Goods/ajaxProperty');
					}else{
						// dump($arr);
						$this -> assign('arr',$arr);
						$this -> display('Goods/ajaxProperty');
					}
			}
		}

		/**
		 * [addGoods 添加spu产品的以及以下一个sku产品的函数]
		 */
		public function addGoods(){

			$data = $_POST;
			$proModel = D('Property');
			$config = [
						'exts' =>['jpg','jpeg','png','gif'],
						'rootPath' => './Public',
						'savePath' => '/Uploads/goods/',
					  ];
			$fileUpload = new \Think\Upload($config);

			//判断有没有上传tupian 
			if(empty($_FILES['info_photo'])){
				$this -> error('商品主图必须添加',U('Goods/addIndex'));
			}else{
				if($info = $fileUpload -> upload()){

		   			//上传数据
		   			$data['imgUrl'] = $info['info_photo']['savepath'].$info['info_photo']['savename'];

		   			
		   		}else{
		   			$this -> error('图片上传失败',U('Goods/addIndex'));
		   		}
			}
			// dump($data);
			$info = $proModel->addGoods($data);
			if($info['flag']){
				$this -> redirect('Goods/addPhotoIndex',['spuid'=>$info['spuid']]);
			}else{
				$this -> error($info['mess'],U('Goods/addIndex'));
			}
		}

		/**
		 * [添加spu下多图的函数]
		 */
		public function addPhotoIndex(){
			if(empty($_GET['spuid'])){
				$this -> error('请先添加商品之后，在上传图片',U('Goods/addIndex'));
			}else{
				$this -> assign('spuid',$_GET['spuid']);
				$this -> display();
			}
			
		}


		/**
		 * 添加商品图片额操作 配合ajax
		 */
		public function addPhoto(){
			if(IS_AJAX){
				$spuid = $_POST['spuid'];
				$config = [
						'exts' =>['jpg','jpeg','png','gif'],
						'rootPath' => './Public',
						'savePath' => '/Uploads/goods/',
					  ];
				$fileUpload = new \Think\Upload($config);
				if($info = $fileUpload -> uploadOne($_FILES['photo'])){

					//将图片存入数据库
					if(M('goodsimg') -> add(['spuId'=>$spuid,'imgUrl'=>$info['savepath'].$info['savename']])){
						$this -> ajaxReturn(['code'=>0,'mess'=>$info['name'].'图片上传成功']);
					}else{
						$this -> ajaxReturn(['code'=>1,'error'=>$info['name'].'图片上传失败,'.$fileUpload->getError()]);
					}
					
				}else{
					$this -> ajaxReturn(['code'=>1,'error'=>$info['name'].$fileUpload->getError()]);
				}	
			}
			
				// dump($_FILES);
		}


		/**
		 * [deleteSpuGoods 多表连删相关的spu所有的子产品]
		 * @return [type] [description]
		 */
		public function deleteSpuGoods(){

			if(empty($_GET['spuid'])){
				$this -> ajaxReturn(['code'=>1,'mess'=>'删除失败']);
			}else{

				//多表连删
				$sql = 'delete gd,gimg,pk,gdd,gsk,st from goods gd inner join goodsImg gimg on gimg.spuId=gd.id inner join spu_sku pk on pk.spuId=gd.id inner join goodsDetail gdd on gdd.skuId = pk.skuId inner join goods_sku gsk on gsk.skuId = gdd.skuId inner join store st on st.skuId = gdd.skuId where pk.spuid='.$_GET['spuid'];
				if(M('')-> execute($sql)){
					$this -> ajaxReturn(['code'=>0,'mess'=>"删除成功"]);
				}else{
					$this -> ajaxReturn(['code'=>1,'mess'=>'删除失败']);
				}
			}	
		}

		/**
		 * [look_sku 用于ajax请求的查询该spuId的所有sku数据]
		 * @return [type] [description]
		 */
		public function look_sku(){
			$goodModel = D('Goods');

			$data = $goodModel -> getskuBySpuid($_GET['spuid']);

			if($data){
				$this -> ajaxReturn(['html'=>$this -> getskuHtml($data),'code'=>0]);
			}else{
				$this -> ajaxReturn(['html'=>'','code'=>1]);
			}

		}

		public function getskuHtml($skuArr){
			$html ='';
			foreach($skuArr as $key => $sku){
				$html.=			'<tr>
									<td>'.$sku['skuid'].'</td>
									<td><img src="'.GOODSIMGPATH.$sku['img'].'" width="30px" height="30px" alt="">'.$sku['gname'].'</td>
									<td>'.$sku['rules'].'</td>
									<td>'.$sku['price'].'</td>
									<td>'.$sku['store'].'</td>
									<td>
										<button type="button" data-skuid="'.$sku['skuid'].'" class="btn btn-danger btn-xs skudelBtn">删除</button>
										<button type="button" class="btn btn-info btn-xs btn-look" data-skuid="'.$sku['skuid'].'">查看</button>
										<a href=""><button type="button" class="btn btn-success btn-xs" data-skuid="'.$sku['skuid'].'">编辑</button></a>
									</td>
								</tr>';
			}

		  return $html;
		}


		/**
		 * [addsku 用于输出显示addsku的页面]
		 * @return [type] [description]
		 */
		public function addsku(){
			if(!empty($_GET['spuid'])){
				$spuid = $_GET['spuid'];

				//查询该spu产品所属的分类
				$cat  = M('goods')->field('cat.name,cat.id cid,gd.name gname') -> alias('gd') -> join('__CATEGORY__ cat ON cat.id = gd.catId')
						   -> where(['gd.id'=>$spuid])
						   -> find();

			    if($cat['cid']){
			    	$parentTree = D('Home/Tree') -> getParentTree($cat['cid']);
			    	$catlist = D('Home/Tree')->getHtmlCate($parentTree,'>');
			    }else{
			    	$catlist = '';
			    }

			
				//查询给spuid的产品品牌
			    $brand = M('brand') -> alias('bd')
			    		   -> join('__GOODS_BRAND__ gbd ON gbd.brandId = bd.id')
			    		   -> join('__GOODS__ gd ON gd.id=gbd.goodsId')
			    		   -> where(['gd.id'=>$spuid])
			    		   -> find();

			   	$this -> assign('brand',$brand);
			   	$this -> assign('cat',$catlist);
			   	$this -> assign('product',$cat);
 				$this -> display();
			}else{
				$this -> error('你还没有选择要在哪个商品下添加！',U('Goods/index'));
			}
			
		}

		/**
		 * [doaddsku 添加sku的产品的函数]
		 * @return [type] [description]
		 */
		public function doaddsku(){
			// dump($_POST);
			// exit;
			if(empty($_POST['spuid'])){
				$this -> error('非法操作！',U('Goods/index'));
			}else{
				$goodModel = D('Goods');
				$data = $_POST;
				if(empty($data['property'])){
					$data['property'] = 0;
				}
				if(empty($data['val'])){
					$data['val'] = 0;
				}
				$info = $goodModel -> addGoods($data);
				if($info['flag']){
					$this->success('添加sku产品成功!',U('Goods/index'));
				}else{
					$this -> error($info['mess'],U('Goods/index'));
				}
			}
		}

		/**
		 * [saveSpu 保存商品信息的函数]
		 * @return [type] [description]
		 */
		public function saveSpu(){

			if(empty($_GET['spuid'])){
				$this -> error('非法操作',U('Goods/index'));
			}else{
				$spuid = $_GET['spuid'];
				if(M('goods')->add(['name'=>$_GET['goodsname'],'id'=>$spuid,'catId'=> $_GET['cat']],'',['catId','name'])>=0){

					if(M('goods_brand')->where(['goodsId'=>$spuid])->save(['brandId'=>$_GET['brand']])){
						$this -> ajaxReturn(['mess'=>'保存成功','code'=>0]);
					}else{
						$this -> ajaxReturn(['mess'=>'商品信息保存成功,品牌信息保存失败','code'=>0]);
					}
					
				}else{
					$this -> ajaxReturn(['mess'=>'商品信息保存失败','code'=>1]);
				}
			}
			
		}



		public function deleteSku(){
			if(empty($_GET['skuid'])){
				$this -> error('抱歉非法操作',U('Goods/index'));
			}else{
				$sql = 'delete pk,gdd,gsk,st from spu_sku pk inner join goodsDetail gdd ON gdd.skuId=pk.skuId inner join store st ON st.skuId=gdd.skuId inner join goods_sku gsk ON gsk.skuId = gdd.skuId where pk.skuId='.$_GET['skuid'];

				if(M('') -> execute($sql)){
					$this -> ajaxReturn(['mess'=>'商品信息保存成功','code'=>0]);
				}else{
					$this -> ajaxReturn(['mess'=>'商品信息保存失败','code'=>1]);
				}
			}
		}

	}